<style lang="less">
@import "gpsReal.less";
</style>
<template>
  <div id="containerMap1">
    <div id="container" ></div>
    <div id="containerTree">
      <Row>
        <Tabs type="card" @on-click="onTabClick">
          <TabPane label="河流"><Tree  v-if="tabIndex == 0" :data="data1" @on-select-change="onTreeChange"></Tree></TabPane>
          <TabPane label="沟渠"><Tree  v-if="tabIndex == 1" :data="data2" @on-select-change="onTreeChange"></Tree></TabPane>
          <TabPane label="水库"><Tree  v-if="tabIndex == 2" :data="data3" @on-select-change="onTreeChange"></Tree></TabPane>
        </Tabs>
      </Row>
    </div>
    <Spin size="large" fix v-if="spinShow" style="z-index: 999;"></Spin>
    <Drawer :title="drawerTitle" :closable="false" width="40" scrollable v-model="drawerFlag">
      <Row>
        <h4>所属区域:{{riverUser.withDepartmentName}}</h4>
        <br>
        <h4>河流类型:{{typeTitle}}</h4>
        <br>
        <h3>设备信息</h3>
        <Table border :columns="equColumns" :data="equData" ref="table"></Table>
      </Row>
    </Drawer>
  </div>

</template>


<script>
  import MapLoader from '@/plugins/amap.js';
  import {
      getCgqimg,
      getCloseimg,
      getJkimg,
      getPathArray,
      getSharpimg,
      getGzimg
  } from '@/plugins/mapPoint.js';
export default {

  name: "gpsReal",
  data() {
    return {
      map:null,
      spinShow:true,
      data1: [],
      data2: [],
      data3: [],
      equData:[],
      equipmentsData:[],
      typeTitle:"河流",
      riverUser:{},
      tabIndex:0,
      equColumns: [
        {
          title: "设备名称",
          key: "equipmentName",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "设备类型",
          key: "equipmentType",
          minWidth: 100,
          sortable: false,
          render: (h, params) => {
            return h("span", params.row.equipmentType == "1"?"摄像头":"水质监测仪");
          }
        },
        {
          title: "经度",
          key: "lon",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "纬度",
          key: "lat",
          minWidth: 120,
          sortable: false,
        },
      ],
      drawerFlag:false,
      drawerTitle:""
    };
  },
  methods: {
    //初始化
    init() {
      let that = this;
      that.getRiverData();
      MapLoader().then(AMap => {
        that.map =new AMap.Map("container", {
          zoom:11.45,
          zooms:[11,15],
          center:[116.70,40.16],
          pitch: 0,
          viewMode: '3D',
          resizeEnable: true,
          layers: [
            // 卫星
            new AMap.TileLayer.Satellite(),
            // 路网
            new AMap.TileLayer.RoadNet()
          ],
        });
      that.getEquipmentsData();
      that.addPolygon();
        that.spinShow = false;
      }, e => {
        console.log('地图加载失败' ,e)
      })

    },
    //获取设备数据
    getEquipmentsData:function(){
      let that = this;
      this.getRequest("/equipments/getAll").then(res => {
        if (res.success) {
          that.equipmentsData = res.result;
          that.addMarkers();
        }
      });
    },
    //获取河流数据
    getRiverData:function(){
      let that = this;
      this.getRequest("/river/getAll").then(res => {
        if (res.success) {
          let hlData = [];
          let gqData = [];
          let skData =  [];
          let riverData = res.result;
          if(riverData.length> 0){
            for(let i = 0;i < riverData.length;i++){
              if("0" == riverData[i].type){
                hlData.push({title:riverData[i].riverName,id:riverData[i].id});
              }else if("1" == riverData[i].type){
                gqData.push({title:riverData[i].riverName,id:riverData[i].id});
              }else if("2" == riverData[i].type){
                skData.push({title:riverData[i].riverName,id:riverData[i].id});
              }
            }
            that.data1=hlData;
            that.data2=gqData;
            that.data3=skData;
          }
        }
      });
    },
    //画地图点(按群组画)
    addMarkers:function(){
      let that = this;
      let lnglats = that.equipmentsData;
      var markers = [];
      let cgqimg = getCgqimg();
      let jkImg = getJkimg();
      let gzImg = getGzimg();
        //传感器图标
      var cgqIcon = new AMap.Icon({
        size: new AMap.Size(50, 50),
        image: cgqimg,
        imageSize: new AMap.Size(48, 48),
      });
      //故障设备图标
      var gzIcon = new AMap.Icon({
        size: new AMap.Size(50, 50),
        image: gzImg,
        imageSize: new AMap.Size(48, 48),
      });
      //监控图标
      var jkIcon = new AMap.Icon({
        size: new AMap.Size(50, 50),
        image: jkImg,
        imageSize: new AMap.Size(48, 48),
      });
      for (var i = 0; i < lnglats.length; i++) {
        var lnglat = lnglats[i];
        let icon;
        let title = lnglat.equipmentName;
        if(lnglat.fault == '1'){
          icon=gzIcon;
          title += '（故障）';
        }else if(lnglat.equipmentType == 1){
            icon = jkIcon;
        }else{
          icon = cgqIcon;
        }


        let content = [];
        /*content.push("<img src='http://tpc.googlesyndication.com/simgad/5843493769827749134'>地址：北京市朝阳区阜通东大街6号院3号楼东北8.3公里");
        content.push("电话：010-64733333");
        content.push("<a href='https://ditu.amap.com/detail/B000A8URXB?citycode=110105'>详细信息</a>");*/
        content.push("所属河流:"+lnglat.riverName +
                "<br/>"+
                "位置坐标:<br/>"+
                "&nbsp;&nbsp;&nbsp;&nbsp;经度:"+lnglat.lon+
                "<br/>"+
                "&nbsp;&nbsp;&nbsp;&nbsp;纬度:"+lnglat.lat+
                "<br/>"+
                "详细信息:"+lnglat.bak );
        // content.push(lnglat.bak);
        // content.push("<br/>");
        // content.push("<a href="+lnglat.address+" target='_blank'>详细信息</a>");
        // 创建点实例
        let marker = new AMap.Marker({
          title:lnglat.equipmentName,
          animation:"AMAP_ANIMATION_DROP",
          position: new AMap.LngLat(lnglat.lon, lnglat.lat),
          icon: icon,
          extData: {
            id: lnglat.id
          }
        });
        marker.content = this.createInfoWindow(title,content);
        marker.on('click', that.markerClick);
        // marker.emit('click', {target: marker});
        markers.push(marker);
      }
      this.map.add(new AMap.OverlayGroup(markers));
      // this.map.clearInfoWindow();
    },
    //标点点击事件
    markerClick:function(e) {
      var infoWindow = new AMap.InfoWindow({isCustom:true,closeWhenClickMap:true,offset: new AMap.Pixel(30, -40)});
      infoWindow.setContent(e.target.content);
      infoWindow.open(this.map, e.target.getPosition());
  },
  //构建自定义信息窗体
  createInfoWindow:function(title, content) {
    let that = this;
    var info = document.createElement("div");
    info.className = "custom-info input-card content-window-card";


    //可以通过下面的方式修改自定义窗体的宽高
    info.style.width = "300px";
    // 定义顶部标题
    var top = document.createElement("div");
    var titleD = document.createElement("div");
    var closeX = document.createElement("img");
    top.className = "info-top";
    titleD.innerHTML = title;
    titleD.onclick = that.map.clearInfoWindow( );
    closeX.src = getCloseimg();
    closeX.onclick = that.mapClearInfoWindow;
    // closeX.setAttribute("click", that.mapClearInfoWindow);

    top.appendChild(titleD);
    top.appendChild(closeX);
    info.appendChild(top);

    // 定义中部内容
    var middle = document.createElement("div");
    middle.className = "info-middle";
    middle.style.backgroundColor = 'white';
    middle.innerHTML = content;
    info.appendChild(middle);

    // 定义底部内容
    var bottom = document.createElement("div");
    bottom.className = "info-bottom";
    bottom.style.position = 'relative';
    bottom.style.top = '0px';
    bottom.style.margin = '0 auto';
    var sharp = document.createElement("img");
    sharp.src = getSharpimg();
    bottom.appendChild(sharp);
    info.appendChild(bottom);
    return info;
  },

    //关闭地图弹窗
    mapClearInfoWindow:function(){
      this.map.clearInfoWindow();
    },

    //画地图遮罩
    addPolygon:function(){
      let that = this;
     /* new AMap.DistrictSearch({
        extensions:'all',
        subdistrict:0
      }).search('顺义区',function(status,result) {*/
        // 外多边形坐标数组和内多边形坐标数组
        // var outer = [
        //   new AMap.LngLat(-180,90,true),
        //   new AMap.LngLat(-180,-90,true),
        //   new AMap.LngLat(180,-90,true),
        //   new AMap.LngLat(180,90,true),
        // ];
        // var holes = result.districtList[0].boundaries
        // var pathArray = [
        //     outer
        // ];
        //顺义区地图遮罩边界
        var holes = getPathArray();
       var polygon = new AMap.Polygon( {
          path:holes,
          strokeColor: 'rgb(0,0,0)',
          strokeWeight: 3,
          strokeOpacity:1,
          fillColor: 'rgba(255,255,255)',
          fillOpacity: 0,
          strokeStyle:'dashed',
          strokeDasharray:[10,2]
        });
        // polygon.setPath(holes);
        that.map.add(polygon);
      // })
    },

    //点击页面树开启右侧详情
    onTreeChange:function(data){

      if(data.length>0){
        data[0].selected = false;
        this.getRiverInfo(data[0].id);
        this.drawerTitle = data[0].title;
        this.drawerFlag = true;
      }
    },

    getRiverInfo:function(riverId){
      let that = this;
      this.spinShow = true;
      this.getRequest("/river/get/"+riverId).then(res => {
        this.spinShow = false;
        if (res.success) {
          that.riverUser = res.result;
          this.equData = res.result.equipments;
        }
      });
    },

    //记录tab标签索引
    onTabClick:function (data) {
      if("0" == data){
        this.typeTitle = "河流";
      }else if("1" == data){
        this.typeTitle = "沟渠";
      }else if("2" == data){
        this.typeTitle = "水库";
      }
      this.tabIndex = data;
    }
  },
  mounted(){
    this.init();
  },

  created() {
  },
};
</script>

